package com.example.oauth2authserver.service.impl;

import com.example.oauth2authserver.model.Role;
import com.example.oauth2authserver.security.SecurityUser;
import com.example.oauth2authserver.model.User;
import com.example.oauth2authserver.service.IRoleService;
import com.example.oauth2authserver.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class UserServiceDetail implements UserDetailsService {
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUserName(username);
        log.info("登录用户：{}",username);
        if (user == null) {
            log.info("登录用户：{} 不存在",username);
            throw new UsernameNotFoundException("登录用户" + username + "不存在");
        }
        List<Role> roles = roleService.findRolesByUserId(user.getId());
        SecurityUser securityUser = null;
        try {
            securityUser = new SecurityUser(user.getId(),user.getUsername(),user.getPassword(),roles);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return securityUser;
    }
}
